#include "stdafx.h"

#pragma execution_character_set("utf-8")

#include <QtWidgets/QApplication>
#include <QWebSocketServer>
#include <QImage>
#include <QByteArray>
#include <QJSValue>
#include <QQmlEngine>

#include "TServer.h"
#include "TCpu.h"
#include "HelperFunctions.h"
#include "Constants.h"
#include "ClientManager.h"
#include "TaskManager.h"
#include "ItemsModel.h"
#include "TSearcherWindow.h"
#include "GlobalHotkey.h"
#include "ItemFoundDialog.h"
#include "ItemsManager.h"
#include <qqml.h>

static QJSValue qmlNativeCppProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    // Export items model to qt quick.
    auto obj = scriptEngine->newObject();
    obj.setProperty("itemsModel", scriptEngine->newQObject(ItemsManager::instance()->mainItems()));

    // Set QQuickWidget's backgroud color.
    int r, g, b, a;
    TSearcherWindow::instance()->palette().brush(QPalette::Background).color().getRgb(&r, &g, &b, &a);
    obj.setProperty("backgroundColor", QString("#%1%2%3").arg(r, 2, 16).arg(g, 2, 16).arg(b, 2, 16));

    return obj;
}

void installTranslator()
{
    QTranslator *tranlator = new QTranslator;
    tranlator->load(":/TSearcher/tsearcher_zh.qm");
    QCoreApplication::instance()->installTranslator(tranlator);
}

void setWindowIcon()
{
    QIcon icon;
    icon.addFile(":/TSearcher/find_128px.ico");
    icon.addFile(":/TSearcher/find_96px.ico");
    icon.addFile(":/TSearcher/find_72px.ico");
    icon.addFile(":/TSearcher/find_64px.ico");
    icon.addFile(":/TSearcher/find_48px.ico");
    icon.addFile(":/TSearcher/find_32px.ico");
    icon.addFile(":/TSearcher/find_24px.ico");
    icon.addFile(":/TSearcher/find_16px.ico");
    static_cast<QApplication *>(QApplication::instance())->setWindowIcon(icon);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qmlRegisterSingletonType("HappyXiaox.Native", 1, 0, "Cpp", &qmlNativeCppProvider);
    setWindowIcon();
    installTranslator();

    auto cpu = TCpu::instance();
    ClientManager::instance();
    TServer::instance();
    ItemsManager::instance();

    TSearcherWindow w;
    w.show();

    GlobaoHotkeyEventFilter::registerThis();
    return app.exec();
}